<script setup lang="ts">
import { ref, onBeforeMount, onMounted,computed,nextTick,h} from 'vue'
import {ElMessage as message } from 'element-plus'
import {setTableHeight, setFixedColumnWidth } from '@/common/utils'
import useRequestList,{actionKeys} from './requestList'
import useRouteList from '@/views/sysAuth/route/routeList'
import MyTable from "@/components/Table/myTable.vue";
import searchPanel from '@/components/SearchPanel'
import Add from './add.vue'
import Update from './update.vue'

const columns = ref<tableColConfig[]>([
	{
		label: '请求名',
		prop: 'requestName',
		columnKey: 'requestName',
		minWidth: 150,
		align: 'center',
	},
	{
		label: '请求路径',
		prop: 'requestPath',
		columnKey: 'requestPath',
		minWidth: 150,
		align: 'center',
		showOverflowTooltip:true,
	},
	{
		label: '授权才能访问',
		prop: 'needAuth',
		columnKey: 'needAuth',
		minWidth: 120,
		align: 'center',
		contentRender: (scope:any) => {
      const v=scope.row.needAuth;	
      return v ? h('span', { style: { color: 'rgb(29, 165, 122)' } }, '是') : h('span', { style: { color: 'rgb(245, 108, 108)' } }, '否')
		},
	},
	{
		label: '描述',
		prop: 'description',
		columnKey: 'description',
		minWidth: 120,
		align: 'center',
		showOverflowTooltip:true
	},
	{
		label: '所属页面路由名集合',
		prop: 'routeNames',
		columnKey: 'routeNames',
		minWidth: 150,
		align: 'center',
		showOverflowTooltip:true
	},
	{
		label: '所属页面标题集合',
		prop: 'routeTitles',
		columnKey: 'routeTitles',
		minWidth: 120,
		align: 'center',
		showOverflowTooltip:true
	},
	{
		label: '操作',
		prop: 'operation',
		columnKey: 'operation',
		width: 128,
		align: 'center',
		fixed: 'right',
	},
])
const isSearching = ref(false)
const searchList = ref<RoleItem[]>([])
const tableHeight = ref<number>()
const addModalVisible = ref(false);
const updateModalVisible = ref(false);
const editRequest = ref({} as requestItem);
const addRef = ref<InstanceType<typeof Add>>()
const updateRef = ref<InstanceType<typeof Update>>()
const tableRef = ref<InstanceType<typeof MyTable>>()
const requestList = useRequestList()
const routeList=useRouteList()
const pageList=ref<selectOption[]>([])
const searchOptions=ref<searchOptionType[]>([
	{type:'input',id:'requestName',props:{label:'请求名'}},
	{type:'input',id:'description',props:{label:'描述'}},
	{type:'select',id:'routeId',props:{label:'所在页面'},innerComponentProps:{filterable:true,optionFilterProp:'label',selectOptions:[],
	}},
	{type:'select',id:'needAuth',props:{label:'是否需要授权'},innerComponentProps:{filterable:true,optionFilterProp:'label',selectOptions:[
		 { label: '是', value: 1 },
		 { label: '否', value: 0 },
	],
	}},
])

const tableData = computed(() => {
	if (!tableRef.value) return []
	const pageNum = tableRef.value!.pageNum
	const pageSize = tableRef.value!.pageSize
	return JSON.parse(JSON.stringify(requestList.list)).splice((pageNum - 1) * pageSize, pageSize)
})

onBeforeMount(() => {
  requestList.getList()
	getPageList()
	searchOptions.value.forEach(v=>{
		if(v.id==='routeId')  
		v.innerComponentProps!.selectOptions=pageList.value
	})
});

onMounted(() => {
  setFixedColumnWidth([actionKeys.update,actionKeys.delete],columns)
});


function handleSearchPanelcollapsed(h:number){
	setTableHeight({tableHeightRef:tableHeight,otherSectionHeight:h})
}

function getPageList(){
	routeList.list.forEach(v=>{
     if(v.component && !v.noNeedAuth && !v.link) pageList.value.push({label:v.title,value:v.id,...v})
	})
}

function search(value:objType){
   //console.log(value)
	 let _searchList=JSON.parse(JSON.stringify(requestList.list))
   if(value.requestName) _searchList=_searchList.filter((v:requestItem)=>v.requestName===value.requestName)
   if(value.description) _searchList=_searchList.filter((v:requestItem)=>v.description.includes(value.description) || value.description.includes(v.description))
   if(value.routeId) _searchList=_searchList.filter((v:requestItem)=>v.routeIds?.includes(value.routeId))
	 if(value.needAuth || value.needAuth==0) _searchList=_searchList.filter((v:requestItem)=>v.needAuth==value.needAuth)
	 searchList.value=_searchList
	 isSearching.value=true
}

function reset() {
  isSearching.value = false
  requestList.getList();
  tableRef.value?.reset()
}
function handleAdd() {
  addModalVisible.value = true;
  nextTick(()=>{addRef.value?.init()})
}
async function handleAddCommit() {
  const isSuccess=await addRef.value?.formCommit()
  if (isSuccess) {
    addModalVisible.value = false;
    message.success("新增成功");
  }
}
function handleUpdate(row: requestItem) {
  editRequest.value = row;
  updateModalVisible.value = true;
  nextTick(()=>{updateRef.value?.init()})
}
async function handleUpdateCommit() {
    const isSuccess=await updateRef.value?.formCommit()
  if (isSuccess) {
    updateModalVisible.value = false;
    message.success("更新成功");
  }
}
async function handleDelete(row: requestItem) {
  const res = await requestList.deleteItem(row.id);
  if (res.code) {
    message.success("删除成功");
  }
}
</script>

<template>
  <div class="userManage">
    <search-panel :options="searchOptions"  @collapsed="handleSearchPanelcollapsed" @reset="reset" @search="search" />
    <div class="tableTool">
      <el-button type="primary" style="margin-right: 5px" @click="handleAdd"
      v-if="$hasAuth([actionKeys.add])">新增请求</el-button
      >
    </div>
    <my-table
      :data="isSearching ? searchList : tableData"
      :columns="columns"
      size="small"
      style="width: 100%"
      class="myTable"
      rowKey="name"
      :maxHeight="tableHeight"
      :pagination="{
        pageSizes: [10, 20, 30, 40, 50],
        small: true,
        background: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total:isSearching ? searchList.length : requestList.list.length,
      }"
      ref="tableRef"
    >
        <template #operation="{row}">
          <el-button type="primary" size="small" @click="handleUpdate(row)" v-if="$hasAuth([actionKeys.update])">修改</el-button>
						<el-popconfirm title="确定要删除吗?" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDelete(row)" v-if="$hasAuth([actionKeys.delete])">
							<template #reference><el-button type="danger" size="small" >删除</el-button></template>
						</el-popconfirm>
        </template>
    </my-table>

    <el-dialog v-model="addModalVisible" title="新增请求" width="80%" :modal="false" draggable :close-on-click-modal="false" align-center>
			<Add  ref="addRef"  :pageList="pageList" />
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="addModalVisible = false">取消</el-button>
					<el-button type="primary" @click="handleAddCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="updateModalVisible" title="更新请求" width="80%" :modal="false" draggable :close-on-click-modal="false" align-center>
			<Update :editRequest="editRequest" :pageList="pageList"   ref="updateRef" />
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="updateModalVisible = false">取消</el-button>
					<el-button type="primary" @click="handleUpdateCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>
  </div>
</template>

<style scoped lang="scss">
.userManage {
  .tableTool {
    padding: 10px 0;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  :deep(.el-table thead .el-table__cell) {
		text-align: center ;
		// background-color: rgb(232, 246, 241) !important;
}
}
</style>
